package com.per.yyyFrame.config.ureport;

import com.bstek.ureport.provider.report.ReportFile;
import com.bstek.ureport.provider.report.ReportProvider;
import com.google.common.collect.ImmutableMap;
import com.per.yyyFrame.common.InvocationHandler;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class DbReportProvider implements ReportProvider {
    private static final String NAME = "数据库";
    private String prefix = "rc:";
    private boolean disable = false;

    @Resource
    InvocationHandler invocationHandler;

    //加载单个模板
    @SneakyThrows
    @Override
    public InputStream loadReport(String fileName) {
       List<Map> data=(List<Map>) invocationHandler.execute("select id,name,fileName,content,createTime,updateTime,previewPath from tmpl_report where fileName=?",
               new ArrayList(){{add("id");add("name");add("fileName");add("content");add("createTime");add("updateTime");add("previewPath");}},
               new ArrayList(){{add(fileName);}});

        Map map = new HashMap();
        map.put("fileName", getNoCorrectName(fileName));
        byte[] res = new byte[0];
        if(data.size()==0){
            data.add(new HashMap());
        }else{
           res = data.get(0).get("content").toString().getBytes();
        }

        InputStream stream = new ByteArrayInputStream(res);
        return stream;
    }

    //删除某个模板
    @SneakyThrows
    @Override
    public void deleteReport(String fileName) {
        if (fileName != null) {
            fileName = getNoCorrectName(fileName);

            Map map = new HashMap();
            map.put("fileName", fileName);
            String finalFileName = fileName;
            invocationHandler.execute("delete from where fileName=?",new ArrayList(),new ArrayList(){{add(finalFileName);}});

        }
    }

    //查询所有模板文件
    @SneakyThrows
    @Override
    public List<ReportFile> getReportFiles() {
        List<Map> list = (List<Map>) invocationHandler.execute("select id,name,fileName,content,createTime,updateTime,previewPath from tmpl_report",
                new ArrayList(){{add("id");add("name");add("fileName");add("content");add("createTime");add("updateTime");add("previewPath");}},
                new ArrayList());

        List<ReportFile> reportFiles = new ArrayList();
        for (Map item : list) {
            SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //加上时间
            try {
                Date date =new Date();
                if(item.get("updateTime")!=null){
                    date = sDateFormat.parse(item.get("updateTime").toString());
                }
            if(item.get("fileName").toString().contains(prefix)){
                reportFiles.add(new ReportFile(item.get("fileName").toString().substring(prefix.length()), date));
            }else{
                reportFiles.add(new ReportFile(item.get("fileName").toString(), date));
            }

            } catch (ParseException px) {
                px.printStackTrace();
            }
        }
        return reportFiles;
    }


    //保存模板
    @SneakyThrows
    @Override
    public void saveReport(String fileName, String content) {
        fileName = getNoCorrectName(fileName);

        Map map = new HashMap();
        map.put("fileName", fileName);

        String finalFileName = fileName;
        List<Map> data =(List<Map>) invocationHandler.execute("select id from tmpl_report where fileName=?",new ArrayList(){{add("id");}},new ArrayList(){{add(finalFileName);}});

        Map param = new HashMap();
        if (data == null||data.size()==0||(data.size()>0&&data.get(0)==null)) {

            invocationHandler.execute("insert into tmpl_report(name,fileName,content)values(?,?,?)",new ArrayList(),new ArrayList(){{
                add(finalFileName.substring(0, finalFileName.indexOf(".")));
                add(finalFileName);
//                add( new Date());
//                add( "/ureport/preview?_u=rc:" + finalFileName + "&_i=1&");
                add( content);
            }});

        } else {
            invocationHandler.execute("update tmpl_report set name=?,fileName=?,updateTime=?,previewPath=?,content=?",new ArrayList<>(),new ArrayList(){{
                add( finalFileName.substring(0, finalFileName.indexOf(".")));
                add( finalFileName);
                add( new Date());
                add( "/ureport/preview?_u=rc:" + finalFileName + "&_i=1&");
                add( content);
            }});
        }
    }

    /**
     * 获取没有前缀的文件名
     *
     * @param name
     * @return
     */
    private String getNoCorrectName(String name) {
        if (name.startsWith(prefix)) {
            name = name.substring(prefix.length());
        }
        return name;
    }

    @Override
    public String getName() {
        return NAME;
    }

    @Override
    public boolean disabled() {
        return disable;
    }

    @Override
    public String getPrefix() {
        return prefix;
    }
}
